﻿using UnityEngine;
using System.Collections;
using System.Collections.Generic;

public class LoadingWindow : MonoBehaviour {
    public static LoadingWindow window
    {
        get
        {
            if (_window == null)
            {
                // Instantiate loading window.
                // Awake() will set its position.
                _window = LTPrefabManager.InstantiateC(PrefabTypes.LoadingWindow) as LoadingWindow;
                UIRoot root = GameObject.Find("UI Root (2D)").GetComponent<UIRoot>();
                if (root != null)
                {
                    Camera cam = root.GetComponentInChildren<Camera>();
                    if (cam != null)
                    {
                        UIAnchor anchor = cam.gameObject.GetComponentInChildren<UIAnchor>();
                        if (anchor != null)
                        {
                            _window.transform.parent = anchor.transform;
                            _window.transform.localPosition = new Vector3(_window.transform.localPosition.x, _window.transform.localPosition.y, -10f);
                            _window.transform.localScale = Vector3.one;
                            _window.GetComponent<UIPanel>().depth = 50;
                        }
                    }
                }
            }
            return _window;
        }
    }

    private static LoadingWindow _window;
    public Transform[] objs;
    public UILabel loadingText;
    public UILabel tip;
    public UILabel tipDesc;

    Transform myTransform;
    Transform loadingImageT;
    BoxCollider _collider;

    void Awake()
    {
        _window = this;
        DontDestroyOnLoad(_window.gameObject);
        //_collider = this.gameObject.collider as BoxCollider;
        _collider = this.gameObject.GetComponentInChildren<BoxCollider>();
        myTransform = transform;
        Application.backgroundLoadingPriority = ThreadPriority.High;
        HideLoading();
    }

    public void ShowInvisibleLoading()
    {
        myTransform.transform.parent = Camera.main.transform;
        objs[5].renderer.material.color = new Color(0, 0, 0, 0.5f);
        for (int i = 0; i < objs.Length; i++) objs[i].renderer.enabled = false;
        //myTransform.position = Windows.GetWindowPosition(Z_Depth.LOADING);
        _collider.size = new Vector3(640, 960, 10);
        isShowShortLoading = false;
        Debug.Log("ShowInvisibleLoading");
    }

    public void ShowShortLoading()
    {
        Debug.LogError("ShowShortLoading");
        //if (Camera.main != null)
        //    myTransform.transform.parent = Camera.main.transform;
        UIRoot root = UIRoot.list[0];
        if (root != null)
        {
            Camera cam = root.GetComponentInChildren<Camera>();
            if (cam != null)
            {
                UIAnchor anchor = cam.gameObject.GetComponentInChildren<UIAnchor>();
                if (anchor != null)
                {
					if( CSceneManager.m_Scene != SCENE.MainScene )
					{
						myTransform.gameObject.layer = anchor.gameObject.layer;
						SetAllChildTransformLayer(myTransform, myTransform.gameObject.layer);
					}
					else
						SetAllChildTransformLayer(myTransform, LayerMask.NameToLayer("GUI_TOP"));
					transform.parent = anchor.transform;
                    transform.localPosition = new Vector3(0, 0, -10f);
                    transform.localScale = Vector3.one;
                }
            }
        }                
        gameObject.SetActive(true);
        //		objs[5].renderer.material.color = new Color(0,0,0,0.2f);

        for (int i = 0; i < objs.Length; i++) objs[i].gameObject.SetActive(true);
        //for (int i = 0; i < 6; i++) objs[i].renderer.enabled = false;
        //for (int i = 6; i < 7; i++) objs[i].renderer.enabled = true;
        //if (myTransform != null)
        //    myTransform.position = Windows.GetWindowPosition(Z_Depth.LOADING);
        if (_collider != null)
            _collider.size = new Vector3(1280, 960, 10);
        isShowShortLoading = true;
        //StopCoroutine("Co_Loading");
        //StartCoroutine("Co_Loading");
        //tipDesc.HideGUI();
        //		timer = 0f;

//		if( CSceneManager.m_Scene == SCENE.InGameScene )
//		{
//			foreach(Transform obj in myTransform)
//			{
//				obj.gameObject.layer = myTransform.parent.gameObject.layer;
//			}
//		}
//		else
//		{
//			foreach(Transform obj in myTransform)
//			{
//				obj.gameObject.layer = myTransform.parent.gameObject.layer;
//			}
//		}
    }

    public void ShowLoading(string message)
    {
        Debug.LogError("ShowLoading");
        myTransform.transform.parent = Camera.main.transform;
        //objs[5].localScale = Vector3.one * 4;
        //objs[5].renderer.material.color = new Color(0.2f, 0.2f, 0.2f, 1.0f);
        loadingText.text = StripPeriods(message);
        //myTransform.position = Windows.GetWindowPosition(Z_Depth.LOADING);
        //for (int i = 0; i < 6; i++) objs[i].renderer.enabled = true;
        //for (int i = 6; i < objs.Length; i++) objs[i].renderer.enabled = false;

        //if (m_LoadingTextLenth < 1)
        //    m_LoadingTextLenth = Tables._dbLoadingTextDB.keys.Count;

        //tip.TextID = Tables._dbLoadingTextDB.GetAt(Random.Range(1, m_LoadingTextLenth)).textID;
        _collider.size = new Vector3(1280, 960, 10);
        //add david for the periods while loading
        //StopCoroutine("LoadingAnimation");
        //StartCoroutine("LoadingAnimation");
        isShowShortLoading = false;
        //		timer = 0f;	

        //tipDesc.ShowGUI();
    }

    public void HideLoading()
    {
        Debug.LogError("HideLoading");
        myTransform.transform.parent = null;
        myTransform.position = Vector3.zero;
        isShowShortLoading = false;
        //add david for the periods while loading
        StopCoroutine("LoadingAnimation");
        for (int i = 0; i < objs.Length; i++) objs[i].gameObject.SetActive(false);
        _collider.size = Vector3.zero;
        //objs[5].localScale = Vector3.one * 4;
        //tipDesc.HideGUI();
    }

    public void SetWindowPosiiton()
    {
        //myTransform.position = Windows.GetWindowPosition(Z_Depth.LOADING);
    }

    string StripPeriods(string _message)
    {
        for (int i = _message.Length - 1; i >= 0; i--)
        {
            if (_message[i] == '.')
                _message = _message.Substring(0, i);
            else
                break;
        }

        return _message;
    }
    Vector3 step = new Vector3(0, 0, 360);
    bool isShowShortLoading = false;

    IEnumerator Co_Loading()
    {
        while (isShowShortLoading)
        {
            objs[6].Rotate(step * Time.deltaTime);
            yield return null;
        }
    }

    //add david for the periods while loading
    IEnumerator LoadingAnimation()
    {
        int numOfPeriods = 0;
        while (true)
        {

            string loadMessage = loadingText.text;

            loadMessage = StripPeriods(loadMessage);

            for (int i = 0; i < numOfPeriods; i++)
                loadMessage += ".";

            numOfPeriods++;


            loadingText.text = loadMessage;

            if (numOfPeriods > 3)
                numOfPeriods = 0;

            yield return new WaitForSeconds(0.4f);
        }
    }
	
	void GetAllChildTransform(Transform t, ref List<Transform> list)
	{
		foreach(Transform child in t)
		{
			list.Add(child);
			GetAllChildTransform(child, ref list);
		}
	}
	
	void SetAllChildTransformLayer(Transform t, int layerIndex)
	{
		t.gameObject.layer = layerIndex;
		foreach(Transform child in t)
		{
			child.gameObject.layer = layerIndex;
			SetAllChildTransformLayer(child, layerIndex);
		}
	}
}
